package com.hktf.corelib.utils;

/**
 * Description: 数据进制间的转换
 * author: hexunwu
 * date: 2017/3/24 10:44.
 */
public class DataTypeConversionUtils {

    //十六进制转换成十进制
    public static String hexadecimalChange(String str) {
        if (str == null) {
            return null;
        }
        String ustrID = str.toUpperCase();
        if (ustrID.contains("0X")) {
            String xstrID = ustrID.substring(ustrID.lastIndexOf("X") + 1, ustrID.length());
            str = String.valueOf(Integer.parseInt(xstrID, 16));
        }
        return str;
    }

    /**
     * 十进制数据转换为十六进制字符串数
     *
     * @param dec
     * @return
     */
    public static String decToHex(String dec) {
        int data = Integer.parseInt(dec, 10);
        return "0x" + Integer.toString(data, 16);
    }

    /**
     * 十六进制数据转换为十进制字符串数
     *
     * @param hex
     * @return
     */
    public static String hexToDec(String hex) {
        int data = Integer.parseInt(hex, 16);
        return Integer.toString(data, 10);
    }

    /**
     * int-->byte
     */
    public static byte[] intToByteArray(final int integer) {
        int byteNum = (40 - Integer.numberOfLeadingZeros(integer < 0 ? ~integer
                : integer)) / 8;
        byte[] byteArray = new byte[4];

        for (int n = 0; n < byteNum; n++)
            byteArray[3 - n] = (byte) (integer >>> (n * 8));

        return (byteArray);
    }

    /**
     * 字节转十六进制
     *
     * @param b 需要进行转换的byte字节
     * @return 转换后的Hex字符串
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    /**
     * 字节转十六进制带0x
     *
     * @param b 需要进行转换的byte字节
     * @return 转换后的Hex字符串
     */

    public static String byteToHexwith(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return "0x" + hex;
    }

}
